package org.rainwalk.bill.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 数值正则
 *
 * @author chenyuheng create class on 2021-06-21
 */
public class PatternNumberValidator implements ConstraintValidator<PatternNumber, Number> {

    private Pattern pattern;

    @Override
    public void initialize(PatternNumber constraintAnnotation) {
        this.pattern = Pattern.compile(constraintAnnotation.regexp());
    }

    @Override
    public boolean isValid(Number value, ConstraintValidatorContext context) {
        if ( value == null ) {
            return true;
        }
        Matcher m = pattern.matcher(value.toString());
        return m.matches();
    }
}
